package com.example.demo.practice.monitor;


import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;


import com.example.demo.practice.R;
import com.example.demo.practice.innerclass.IBaseActivity;
import com.example.demo.practice.monitoring.AllAlarmList;
import com.example.demo.practice.tool.ServerHttp;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HistoricalRecords extends IBaseActivity {
    private LineChart lineChart;
    private ListView listView;
    private List<Map<String, Object>> groupArray;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_historical_records);
        lineChart = (LineChart) findViewById(R.id.lineChart);
        initLineChart(lineChart);
        serverHttp =new ServerHttp(new DateHandler());
        serverHttp.setUrl("getFacilities");
    }


    /**
     * 初始化折线图
     *
     * @param mChart
     */
    private void initLineChart(LineChart mChart) {
        mChart.setViewPortOffsets(0, 0, 0, 0);
        mChart.setBackgroundColor(getResources().getColor(R.color.windowBackground));

        // no description text
        mChart.getDescription().setEnabled(false);

        // enable touch gestures
        mChart.setTouchEnabled(true);

        // enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(false);

        mChart.setDrawGridBackground(false);
        mChart.setMaxHighlightDistance(300);

        XAxis x = mChart.getXAxis();
        x.setEnabled(false);

        YAxis y = mChart.getAxisLeft();
        y.setTypeface(Typeface.SERIF);
        y.setLabelCount(6, false);
        y.setTextColor(Color.WHITE);
        y.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        y.setDrawGridLines(false);
        y.setAxisLineColor(Color.WHITE);

        mChart.getAxisRight().setEnabled(false);

        // add data
        setLineData(20, 50, mChart);

        mChart.getLegend().setEnabled(false);

        mChart.animateXY(2000, 2000);
        mChart.invalidate();

    }

    private void setLineData(int count, int range, LineChart mChart) {
        ArrayList<Entry> yVals = new ArrayList<Entry>();

        for (int i = 0; i < count; i++) {
            float mult = (range + 1);
            float val = (float) (Math.random() * mult) + 20;
            yVals.add(new Entry(i, val));
        }

        LineDataSet set1;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals, "DataSet 1");

            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            set1.setCubicIntensity(0.2f);
            set1.setDrawCircles(false);
            set1.setLineWidth(1.8f);
            set1.setCircleRadius(4f);
            set1.setCircleColor(Color.WHITE);
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setColor(getResources().getColor(R.color.lineChart_fill));
            set1.setFillColor(getResources().getColor(R.color.lineChart_fill));
            set1.setFillAlpha(255);
            set1.setDrawFilled(true);
            set1.setDrawHorizontalHighlightIndicator(false);
            set1.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return -10;
                }
            });

            // create a data object with the datasets
            LineData data = new LineData(set1);
            data.setValueTypeface(Typeface.SERIF);
            data.setValueTextSize(9f);
            data.setDrawValues(false);

            // set data
            mChart.setData(data);
        }
}

    class DateHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            JSONArray jsonArray=serverHttp.getData();
            groupArray = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < jsonArray.length(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                JSONObject json = null;
                try {
                    json = (JSONObject) jsonArray.get(i);
                        map.put("code", json.getString("eqindex"));
                        map.put("type", json.getString("name"));
                        map.put("address", json.getString("address"));
                        map.put("floor", json.getString("floor")+"层");
                        groupArray.add(map);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            jsonArray = null;
            serverHttp.clear();
            //适配列表
            SimpleAdapter simpleAdapter = new SimpleAdapter(HistoricalRecords.this,
                    groupArray,
                    R.layout.list_alarm_all,
                    new String[]{"code", "type", "address", "floor"},
                    new int[]{R.id.code, R.id.company, R.id.address, R.id.name});
            listView= (ListView) findViewById(R.id.list);
            listView.setAdapter(simpleAdapter);
            listView.setDivider(null);
            listView.setOnItemClickListener(new ItemClick());

            super.handleMessage(msg);
        }
    }

    class ItemClick implements AdapterView.OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            setLineData(20, 50, lineChart);
            lineChart.invalidate();
            lineChart.animateXY(1000, 1000);
        }
    }
}
